package com.xj.demo.reference;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;

public class PhantomObjTest {
    static PhantomObjTest obj;
    static ReferenceQueue<PhantomObjTest> phantomQueue = null;

    static class CheckRefQueue extends Thread {
        @Override
        public void run() {
            while (true) {
                if (phantomQueue != null) {
                    PhantomReference<PhantomObjTest> phantomRef = null;
                    try {
                        phantomRef = (PhantomReference<PhantomObjTest>) phantomQueue.remove();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (phantomRef != null) {
                        System.out.println("Phantom Reference has been enqueued.-->" + phantomRef.get());
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        new CheckRefQueue().start();
        obj = new PhantomObjTest();
        System.out.println(obj);
        phantomQueue = new ReferenceQueue<PhantomObjTest>();
        PhantomReference<PhantomObjTest> phantomRef = new PhantomReference<PhantomObjTest>(obj, phantomQueue);
        obj = null;
        System.gc();
        try {
            Thread.sleep(1000);
            System.out.println(phantomRef.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
